import { View } from '@tarojs/components';
import { Video } from '@nutui/nutui-react-taro';
import { Popup, Input, Button } from '@nutui/nutui-react-taro';
import Taro from '@tarojs/taro';
import './index.less';
import { useState, useEffect } from 'react';
import { uploadFileByForm } from '@/tools/upload';
import { getUser } from '@/utils/user';
import { IVideo } from '../..';

interface IProps {
  onRefresh: () => void;
  videoList: IVideo[]
}

export default function Index(props?: IProps) {
  const { videoList = [] } = props || {};
  const [playingList, setPlayingList] = useState<boolean[]>(new Array(videoList.length).fill(true));
  const [showUploadPopup, setShowUploadPopup] = useState(false);
  const [videoName, setVideoName] = useState('');
  const [videoFile, setVideoFile] = useState<any>(null);
  const [uploading, setUploading] = useState(false);

  const handleVideoClick = (index: number) => {
    const videoContext = Taro.createVideoContext(`video-${index}`);

    if(playingList[index]){
      videoContext.play();
    }else{
      videoContext.pause();
    }
    setPlayingList(prev => {
      const newList = [...prev];
      newList[index] = !newList[index];
      return newList;
    });

  };

  const handleUploadClick = () => {
    setShowUploadPopup(true);
  };

  const handleSelectVideo = async () => {
    try {
      const res = await Taro.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back'
      });
      
      setVideoFile(res.tempFilePath);
    } catch (error) {
      console.error('选择视频失败:', error);
      Taro.showToast({
        title: '选择视频失败',
        icon: 'none'
      });
    }
  };

  const handleSubmit = async () => {
    if (!videoFile) {
      Taro.showToast({
        title: '请选择视频',
        icon: 'none'
      });
      return;
    }

    if (!videoName.trim()) {
      Taro.showToast({
        title: '请输入视频名称',
        icon: 'none'
      });
      return;
    }

    setUploading(true);
    try {
      // 获取用户ID
      const userId = getUser().id;
      
      // 上传视频文件
      const uploadRes = await uploadFileByForm('/video/upload', videoFile, {
        userId,
        name: videoName
      })
      // console.log("上传成功", uploadRes);
      const result = uploadRes.data;
      
      if (uploadRes.code === 200) {
        Taro.showToast({
          title: '上传成功',
          icon: 'success'
        });
        setShowUploadPopup(false);
        setVideoName('');
        setVideoFile(null);
        // TODO: 刷新视频列表
        props?.onRefresh();
      } else {
        throw new Error(result.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      Taro.showToast({
        title: error.message || '上传失败',
        icon: 'none'
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <View className="dou-video">
      <View className="video-grid">
        <View className="video-item upload" onClick={() => handleUploadClick()}>
          <View className="upload-icon">+</View>
          <View className="upload-text">上传形象</View>
        </View>
        
        {videoList.map((item, index) => (
          <View 
            key={index} 
            className="video-item"
            onClick={() => handleVideoClick(index)}
          >
            <Video
              id={`video-${index}`}
              source={{
                src: item.url,
                type: 'video/mp4',
              }}
              poster={item.pic}
              options={{
                controls: false,
              }}
            />
            <View className="video-title">{item.name}</View>
            {
              playingList[index] && <View className="video-mask">
                <View className="play-icon">▶</View>
              </View>
            }
          </View>
        ))}
      </View>
      <View className="title">
        <View className="icon" />
        使用说明
      </View>
      <View className="content primary">
        1. 上传一段10秒-1分钟的视频
      </View>
      <View className="content primary">
        2. 上传视频不会消耗cc
      </View>
      <View className="bottom"></View>
      
      <Popup
        visible={showUploadPopup}
        onClose={() => setShowUploadPopup(false)}
        position="bottom"
        round
      >
        <View className="upload-popup">
          <View className="popup-title">上传视频</View>
          <View className="upload-form">
            <View className="form-item">
              <Input
                className="video-name-input"
                placeholder="请输入视频名称"
                value={videoName}
                onChange={(val) => setVideoName(val)}
              />
            </View>
            <View className="form-item">
              <Button 
                className="select-video-btn"
                onClick={handleSelectVideo}
              >
                {videoFile ? '重新选择视频' : '选择视频'}
              </Button>
            </View>
            <View className="form-item">
              <Button 
                className="submit-btn"
                type="primary"
                loading={uploading}
                onClick={handleSubmit}
              >
                上传
              </Button>
            </View>
          </View>
        </View>
      </Popup>
    </View>
  );
}
